// package win.larryzeal.spring.config;/*
//  * SecurityConfiguration
//  * Created by liutong on 2017/4/15.
//  * <p>
//  * Copyright © 2017 中国电信股份有限公司 版权所有
//  * <p>
//  * 所有文字、代码资料，版权均属中国电信股份有限公司所有，任何公司或个人未经
//  * 本司协议授权，不得复制、下载、存储或公开显示。违者本公司将依法追究责任。
//  */
//
// import cn.com.chinatelecom.ecms.service.security.BaseUserDetailsService;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.context.annotation.Bean;
// import org.springframework.context.annotation.Configuration;
// import org.springframework.security.config.annotation.web.builders.HttpSecurity;
// import org.springframework.security.config.annotation.web.builders.WebSecurity;
// import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
// import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
// import org.springframework.security.config.http.SessionCreationPolicy;
// import org.springframework.security.core.userdetails.UserDetailsService;
// import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
// import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
// import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
// import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
// import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
// import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
// import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
// import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
// import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy;
// import org.springframework.security.web.session.ConcurrentSessionFilter;
// import org.springframework.security.web.session.SessionInformationExpiredStrategy;
// import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
// import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
// import org.springframework.session.ExpiringSession;
// import org.springframework.session.FindByIndexNameSessionRepository;
// import org.springframework.session.security.SpringSessionBackedSessionRegistry;
//
// import java.util.ArrayList;
// import java.util.List;
//
// /**
//  * Web 安全认证配置
//  */
// @Configuration
// @EnableWebSecurity(debug = false)
// // @EnableGlobalMethodSecurity(prePostEnabled = true) // 启用 Security 注解
// public class SecurityConfig1 extends WebSecurityConfigurerAdapter {
//     // private final Logger logger = LoggerFactory.getLogger(this.getClass());
//     // 最大 Session 并发
//     private static final int MAXIMUM_SESSION = 5;
//     private FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;
//
//     /**
//      * 配置无需安全检查的路径
//      */
//     @Override
//     public void configure(WebSecurity web) throws Exception {
//         web
//                 /*.debug(true)*/
//                 .ignoring()
//                 .regexMatchers("^$")
//                 .antMatchers("/", "/**/*.js", "/**/*.css", "/**/*.gif", "/**/*.png", "/**/*.jpg", "/**/*.ico")
//                 // .antMatchers("/js/**", "/css/**", "/images/**")
//                 .antMatchers("/monitor.jsp");
//
//         // 自定义 PermissionEvaluator
//         /*DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
//         handler.setPermissionEvaluator(new BasePermissionEvaluator());
//         web.expressionHandler(handler);*/
//     }
//
//     /**
//      * Http 请求认证
//      */
//     @Override
//     protected void configure(HttpSecurity http) throws Exception {
//         http.authorizeRequests() //方法有多个子节点，每个 macher 按照他们的声明顺序执行
//                 // 无需权限验证
//                 .antMatchers("/login", "/passPort", "/secondaryValidation", "/common/**", "/ecs/**").permitAll()
//                 // 求身份验证（登陆）
//                 .antMatchers("/main", "/home", "/ueditor/**", "/traceProcessImage",
//                         "/orderCommon/selectGoodsType**", "/orderCommon/selectOrderStatus**",
//                         "/orderCommon/selectShop**", "/orderCommon/selectCityByProv**",
//                         "/orderCommon/selectAddresseeCityByProv**", "/orderCommon/selectAddresseeCountyByCity**",
//                         "/download/**", "/orderCommon/idcardImage").authenticated()
//                 // 监控页面暂时需要登陆验证(PermissionEvaluator 中没做模糊匹配)
//                 .antMatchers("/monitoring**", "/druid/**").fullyAuthenticated()
//                 // 不是匿名用户、权限验证
//                 .anyRequest().access("isAuthenticated() and @securityService.hasPermission(authentication, request)");
//         //.anyRequest().denyAll();
//
//         // 登陆相关配置
//         /*http.formLogin()
//                 // 制定登陆 URL，并设置访问权限（所有登陆和未登陆的都可以访问）
//                 .loginPage("/login").permitAll()
//                 // 登陆成功后默认默认跳转页面
//                 .defaultSuccessUrl("/main", false);*/
//         http.addFilterAfter(authenticationFilter(), UsernamePasswordAuthenticationFilter.class);
//
//         // 退出由框架实现
//         http.logout()
//                 // 支持 GET 请求（logoutUrl 支持 POST）
//                 .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
//                 // 注销时让 HttpSession 无效、删除 Cookies
//                 /*.clearAuthentication(true)*/.invalidateHttpSession(true)/*.deleteCookies(COOKIE_NAME)*/
//                 // 退出成功后跳转到默认页
//                 .logoutSuccessUrl("/login");
//
//
//         // session 配置
//         http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).sessionAuthenticationStrategy(authenticationStrategy())/*.maximumSessions(1).maxSessionsPreventsLogin(true).expiredUrl("/expired")*/;
//         http.addFilterAt(concurrentSessionFilter(), ConcurrentSessionFilter.class);
//
//         // 非法访问
//         http.exceptionHandling().accessDeniedPage("/common/unauthorized.jsp").authenticationEntryPoint(loginUrlAuthenticationEntryPoint());
//
//         // CSRF 攻击
//         http.csrf().disable();
//         // spring security 安全框架设置了默认的 X-Frame-Options 为 DENY(iframe 不能正常加载)
//         http.headers().frameOptions().sameOrigin().cacheControl().disable();
//     }
//
//     /**
//      * 用户认证 Service，代替 configure(AuthenticationManagerBuilder auth)
//      */
//     @Bean
//     public UserDetailsService userDetailsService() {
//         return new BaseUserDetailsService();
//     }
//
//     /**
//      * 自定义 登陆拦截器
//      */
//     @Bean
//     public UsernamePasswordAuthenticationFilter authenticationFilter() throws Exception {
//         UsernamePasswordAuthenticationFilter authFilter = new UsernamePasswordAuthenticationFilter();
//         // 允许 GET、POST
//         authFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/secondaryValidation"));
//         authFilter.setPostOnly(false);
//         authFilter.setAuthenticationManager(super.authenticationManager());
//         authFilter.setAuthenticationSuccessHandler(savedRequestAwareAuthenticationSuccessHandler());
//         authFilter.setAuthenticationFailureHandler(simpleUrlAuthenticationFailureHandler());
//         authFilter.setUsernameParameter("username");
//         authFilter.setPasswordParameter("password");
//         authFilter.setSessionAuthenticationStrategy(authenticationStrategy());
//         return authFilter;
//     }
//
//     /**
//      * 自定义 Session 并发控制
//      */
//     @Bean
//     public ConcurrentSessionFilter concurrentSessionFilter() {
//         SessionInformationExpiredStrategy expiredStrategy = new SimpleRedirectSessionInformationExpiredStrategy("/common/expired.jsp");
//         ConcurrentSessionFilter filter = new ConcurrentSessionFilter(sessionRegistry(), expiredStrategy);
//         return filter;
//     }
//
//     /**
//      * 登陆地址
//      */
//     @Bean
//     public LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint() {
//         return new LoginUrlAuthenticationEntryPoint("/login");
//     }
//
//     /**
//      * 登陆成功 Handler
//      */
//     @Bean
//     public SavedRequestAwareAuthenticationSuccessHandler savedRequestAwareAuthenticationSuccessHandler() {
//         SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
//         handler.setDefaultTargetUrl("/main");
//         handler.setAlwaysUseDefaultTargetUrl(false);
//         return handler;
//     }
//
//     /**
//      * 登陆失败 Handler
//      */
//     @Bean
//     public SimpleUrlAuthenticationFailureHandler simpleUrlAuthenticationFailureHandler() {
//         return new SimpleUrlAuthenticationFailureHandler("/login");
//     }
//
//     /**
//      * Session 策略配置
//      *
//      * @return
//      */
//     @Bean
//     public SessionAuthenticationStrategy authenticationStrategy() {
//         List<SessionAuthenticationStrategy> strategies = new ArrayList<>();
//         // Seesion 并发控制
//         ConcurrentSessionControlAuthenticationStrategy strategy1 = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
//         strategy1.setMaximumSessions(MAXIMUM_SESSION);
//         // maxSessionsPreventsLogin
//         strategy1.setExceptionIfMaximumExceeded(false);
//         strategies.add(strategy1);
//
//         // Session 固话攻击
//         SessionFixationProtectionStrategy strategy2 = new SessionFixationProtectionStrategy();
//         strategy2.setMigrateSessionAttributes(true);
//         // ChangeSessionIdAuthenticationStrategy strategy2 = new ChangeSessionIdAuthenticationStrategy();
//         strategies.add(strategy2);
//
//         // Session 注册
//         RegisterSessionAuthenticationStrategy strategy3 = new RegisterSessionAuthenticationStrategy(sessionRegistry());
//         strategies.add(strategy3);
//
//         return new CompositeSessionAuthenticationStrategy(strategies);
//     }
//
//     /**
//      * Session 注册表
//      */
//     @Bean
//     public SpringSessionBackedSessionRegistry sessionRegistry() {
//         // return new SessionRegistryImpl();
//         return new SpringSessionBackedSessionRegistry(sessionRepository);
//     }
//
//     @SuppressWarnings({"unchecked", "rawtypes"})
//     @Autowired
//     public void setSessionRepository(FindByIndexNameSessionRepository sessionRepository) {
//         this.sessionRepository = sessionRepository;
//     }
//
//     /*@Autowired
//     public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
//         auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
//         auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
//         auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN", "DBA");//dba have two roles.
//     }*/
//
//     /**
//      * 用户认证
//      */
//     /*@Override
//     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//         auth.userDetailsService(detailsService)*//*.passwordEncoder(new BCryptPasswordEncoder())*//*;
//     }*/
//
//     /**
//      * MainController 自定义登陆时使用
//      */
//     /*@Bean
//     public AuthenticationManager authenticationManager() throws Exception {
//         return super.authenticationManager();
//     }*/
// }
